#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#include<windows.h>
//全局变量
int high, width;//游戏尺寸
int ball_x, ball_y;//小球坐标
int ball_vx, ball_vy;//小球速度
int position_x, position_y;//挡板中心坐标
int left, right;//挡板的左右边界
int radius;//挡板半径大小
int ballnumber;
int goal;//目标
int grade;
//光标移动到x,y位置
void gotoxy(int x, int y) {
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition(handle, pos);
}
//第二个值为0表示隐藏光标
void HideCursur() {
	CONSOLE_CURSOR_INFO cursor_info = { 1,0 };
	SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
//数据初始化
void startup() {
	high = 26;
	width = 30;
	ball_x = 1;
	ball_y = width / 2;
	ball_vx = 1;
	ball_vy = 1;
	position_x = high;
	position_y = width / 2;
	radius = 5;
	left = position_y - radius;
	right = position_y + radius;
	ballnumber = 0;
	grade = 0;
	goal = rand() % width;
	HideCursur();//隐藏光标
}
//显示画面
void show() {
	gotoxy(0, 0);//光标移动到原点位置，以下重画清屏
	int i, j;
	for (i = 0; i <= high; i++) {
		for (j = 0; j <= width; j++) {
			if (i == ball_x && j == ball_y) {
				printf("o");
			}
			else if (j == width) {
				printf("|");//输出右边界
			}
			else if (i == high) {
				printf("_");//输出下边界
			}
			else if (i == position_x - 1 && j >= left && j <= right) {
				printf("*");//输出挡板
			}
			else if (i == 0 && j == goal) {
				printf("#");
			}
			else {
				printf(" ");//输出空格
			}
		}
		printf("\n");
	}
	printf("反弹小球数：%d\n", ballnumber);
	printf("分数：%d\n", grade);
}
//与用户输入无关的更新
void updatewithoutinput() {
	if (ball_x == position_x - 2) {
		if (ball_y >= left && ball_y <= right) {
			ballnumber++;
			ball_vy = ball_vy;
			ball_vx = -ball_vx;
		}
	}
	else if (ball_x == high) {
		printf("Game over");
		exit(0);
	}//小球碰到下边框，游戏结束
	else if (ball_x == 0 && ball_y == goal) {
		goal = rand() % width;
		grade++;
	}
	//根据速度更新小球位置
	ball_x = ball_x + ball_vx;
	ball_y = ball_y + ball_vy;
	//碰到边界，改变速度方向
	if ((ball_x == 0) || (ball_x == high)) {
		ball_vx = -ball_vx;
	}
	if ((ball_y == 0) || (ball_y == width)) {
		ball_vy = -ball_vy;
	}
	Sleep(70);
}
//与用户输入有关的更新
void updatewithinput() {
	char input;
	if (_kbhit()) {
		input = _getch();
		if (input == 'a') {
			position_y--;
			left = position_y - radius;
			right = position_y + radius;
		}
		if (input == 'd') {
			position_y++;
			left = position_y - radius;
			right = position_y + radius;
		}
		if (input == 'w') {
			position_x--;
		}
		if (input == 's') {
			position_x++;
		}
	}
}
int main()
{
	startup();
	while (1) {
		show();
		updatewithoutinput();
		updatewithinput();
	}
	return 0;
}